package com.example.e_comm.controller;

import com.example.e_comm.entity.User;
import com.example.e_comm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public boolean register(@RequestBody User user) {
        try {
            return userService.register(user);
        } catch (IllegalArgumentException e) {
            // 这里可以添加日志记录
            return false;
        }
    }

    @PostMapping("/login")
    public String login(@RequestParam String username, @RequestParam String password) {
        return userService.login(username, password);
    }

    @GetMapping("/info")
    public String getUserInfo(@RequestHeader("Authorization") String token) {
        return userService.getUserInfo(token);
    }

    @PutMapping("/update")
    public String updateUserInfo(@RequestHeader("Authorization") String token,
                                 @RequestBody User user) {
        return userService.updateUserInfo(token, user);
    }

    @PutMapping("/password")
    public String updateUserPassword(@RequestHeader("Authorization") String token,
                                     @RequestParam String oldPassword,
                                     @RequestParam String newPassword) {
        return userService.updateUserPassword(token, oldPassword, newPassword);
    }
    
    @GetMapping("/current")
    public ResponseEntity<?> getCurrentUser(@RequestHeader("Authorization") String token) {
        // 实现获取当前用户信息的逻辑
        String userInfo = userService.getUserInfo(token);
        if (userInfo != null) {
            return ResponseEntity.ok(userInfo);
        } else {
            return ResponseEntity.status(401).body("用户未认证");
        }
    }
}